/*
 * @lc app=leetcode.cn id=61 lang=javascript
 *
 * [61] 旋转链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */

function ListNode(val, next) {
    this.val = (val === undefined ? 0 : val)
    this.next = (next === undefined ? null : next)
}


var rotateRight = function (head, k) {
    let fast = head, slow = head
    let len = 0

    // 边界问题
    if (!head || k === 0) {
        return head
    }

    // 一次遍历计算长度
    while (fast) {
        fast = fast.next
        len++
    }
    fast = head
    k %= len

    // 快指针先走
    while (k-- && fast.next) {
        fast = fast.next
    }

    // 快慢指针一起走
    while (fast && fast.next) {
        fast = fast.next
        slow = slow.next
    }

    // 设定巡回
    fast.next = head
    // 记录返回节点
    var res = slow.next
    // 设置尾节点
    slow.next = null
    return res
};
// @lc code=end



var n3 = new ListNode(2, null)
var n2 = new ListNode(1, n3)
var n1 = new ListNode(0, n2)

rotateRight(n1, 8)
